package week4.day22;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @Author fengzihao
 * @Date 2024-05-06 20:07
 */
public class ReadFIleAndCount {
    public static void main(String[] args) {
        File file = new File("a.txt");
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        int odd = 0;
        int even = 0;
        int num;
        try {
            while ((num = fileInputStream.read())!=-1){
                if (Character.isDigit(num)) {
                    int numData = Character.getNumericValue(num);
                    if (num % 2 == 0) {
                        even++;
                    } else {
                        odd++;
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String evens = "偶数个数:" + even + "个";
        String odds = "奇数个数:" + odd + "个";
        try (FileOutputStream fileOutputStream = new FileOutputStream(file, true)) {
            fileOutputStream.write("\n".getBytes(StandardCharsets.UTF_8));
            fileOutputStream.write(evens.getBytes("UTF-8"));
            fileOutputStream.write("\n".getBytes(StandardCharsets.UTF_8));
            fileOutputStream.write(odds.getBytes("UTF-8"));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
